/**
 * Copyright (C) 2010 OpenWeb Technology Inc.
 */

package photosalvage.logging;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;

/**
 * @author shumpei
 *
 */
public class MethodProfileLogInterceptor implements MethodInterceptor {
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		long start = System.currentTimeMillis();
		try {
			Object result = invocation.proceed();
			long end = System.currentTimeMillis();
			log(invocation, start, end, null);
			return result;
		} catch (Throwable t) {
			long end = System.currentTimeMillis();
			log(invocation, start, end, t);
			throw t;
		}
	}
	
	private void log(MethodInvocation invocation, long start, long end, Throwable t) {
		Method method = invocation.getMethod();
		String className = method.getDeclaringClass().getName();
		String methodName = method.getName();
		String errorName = t != null ? t.getClass().getName() : "";
		
		Object[] logEntries = new Object[] {
				className, methodName, (end - start), errorName
		};
		String log = "\"" + StringUtils.join(logEntries, "\",\"") + "\"";
		Loggers.PERFORMANCE_LOGGER.info(log);
	}
}
